﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Read.API.Command;
using B.S.BaseData.Read.API.DTO;
using MediatR;

namespace B.S.BaseData.Read.API.CommandHandler
{
    public class QueryNavigationHandler : IRequestHandler<QueryNavigationCommand, APIResult<List<NavigationDTO>>>
    {
        private readonly IBaseRepository<Menu> menuRep;
        private readonly IMapper mapper;
        private readonly IBaseRepository<RoleMenu> rmRep;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="menuRep"></param>
        /// <param name="mapper"></param>
        public QueryNavigationHandler(IBaseRepository<Menu> menuRep, IMapper mapper,IBaseRepository<RoleMenu> rmRep)
        {
            this.menuRep = menuRep;
            this.mapper = mapper;
            this.rmRep = rmRep;
        }
        public Task<APIResult<List<NavigationDTO>>> Handle(QueryNavigationCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<NavigationDTO>> result = new APIResult<List<NavigationDTO>>();
            result.Code = APIEnum.Success;
            result.Msg = "查询成功";
            result.Data = GetTree(0,Convert.ToInt32(request.rid));
            return Task.FromResult(result);
        }

        private List<NavigationDTO> GetTree(int pid,int rid)
        {
            var list = (from a in menuRep.GetAll().Where(x => x.PId == pid && !x.IsDeleted)
                       join b in rmRep.GetAll().Where(x => x.RoleId == rid) on a.MenuId equals b.MenuId
                       select new Menu
                       {
                            MenuId=a.MenuId,
                            MenuName=a.MenuName,
                             MenuUrl=a.MenuUrl,
                       }).ToList();
            var res = new List<NavigationDTO>();
            foreach (var item in list)
            {
                var model = new NavigationDTO()
                {
                    value = item.MenuId,
                    label = item.MenuName,
                     path=item.MenuUrl,
                    children= GetTree(item.MenuId,rid)

                };
                res.Add(model);
            }
            return res;
        }
    }
}
